<template>
  <div class="detail">
    <!-- 返回 -->
    <nav-bar
      is-back
      right-width="90px"
      :class="['nav-bar', scrollTop > 256 ? 'scroll-nav-bar' : '']"
    >
      <template #left>
        <i class="iconfont icon-fanhui"></i>
      </template>
      <template #center v-if="scrollTop > 256">
        <div class="center">
          <span :class="{ active: scrollTop > 256 && scrollTop < 700 }">
            商品
            <i class="line"></i>
          </span>
          <span
            :class="{ active: scrollTop >= 700 && scrollTop < goodsDetailTop }"
          >
            详情
            <i class="line"></i>
          </span>
          <span :class="{ active: scrollTop > goodsDetailTop }">
            推荐
            <i class="line"></i>
          </span>
        </div>
      </template>
      <template #right>
        <div class="right">
          <i class="iconfont icon-zhuanfa"></i>
          <i class="iconfont icon-gengduo"></i>
        </div>
      </template>
    </nav-bar>
    <!-- 图片 -->
    <van-swipe
      v-if="loading"
      @change="(index) => (current = index)"
      height="300"
    >
      <van-swipe-item v-for="item in detail.itemInfo.topImages" :key="item.id">
        <img v-lazy="item" width="100%" height="300" />
      </van-swipe-item>
      <template #indicator>
        <div class="custom-indicator">
          {{ current + 1 }} / {{ detail.itemInfo.topImages.length }}
        </div>
      </template>
    </van-swipe>
    <!-- 详情 -->
    <div v-if="loading" class="detail-body">
      <!-- 价格和商品名称 -->
      <info-panel
        :highNowPrice="detail.itemInfo.highNowPrice"
        :desc="detail.detailInfo.desc"
      />
      <!-- 单元格 -->
      <service />
      <!-- 店铺 -->
      <shop-info :shop-info="detail.shopInfo" />
      <!-- 穿着效果 -->
      <goods-detail :detail-info="detail.detailInfo" ref="goodsDetail" />
    </div>
    <!--添加购物车 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="shop-o" text="店铺" />
      <van-goods-action-icon icon="cart-o" text="购物车" />
      <van-goods-action-button
        color="#333"
        text="加入购物车"
        @click="showSku = true"
      />
      <van-goods-action-button
        color="var(--theme-color)"
        text="立即购买"
        @click="showSku = true"
      />
    </van-goods-action>
    <!-- 购买样式数量 -->
    <van-sku
      v-model="showSku"
      :sku="sku"
      :goods="goods"
      :goods-id="gid"
      @buy-clicked="handleBuyClicked"
      @add-cart="handleAddCartClicked"
    >
      <template #sku-actions="props">
        <div class="van-sku-actions">
          <van-button
            square
            color="#333"
            class="sku-action-btn"
            @click="props.skuEventBus.$emit('sku:addCart')"
          >
            加入购物车
          </van-button>
          <van-button
            square
            color="var(--theme-color)"
            class="sku-action-btn"
            @click="props.skuEventBus.$emit('sku:buy')"
          >
            立即购买
          </van-button>
        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { queryGoodsDetail, saveCart } from '@/api'
import { Toast } from '@/utils'
import NavBar from '../../components/nav-bar/nav-bar.vue'
import ShopInfo from './cpn/shop-info/shop-info.vue'
import GoodsDetail from './cpn/goods-detail/goods-detail.vue'
import InfoPanel from './cpn/info-panel/info-panel.vue'
import Service from './cpn/service/service.vue'
export default {
  components: { NavBar, ShopInfo, GoodsDetail, InfoPanel, Service },
  data: () => ({
    gid: 0, //商品id
    detail: {}, // 详情信息
    current: 0, // 轮播指示器
    // 虽然我们在mounted生命周期中请求数据，但是页面已经挂载完成了，但是数据还没拿到，我们直接使用了，就会导致这样的错误，
    // 所以我们一开始在页面渲染的时候不让这一块内容进行渲染，等数据请求完毕，再渲染这一块内容
    loading: false, // 是否加载页面数据
    scrollTop: 0, // 滚动高度
    goodsDetailTop: 0, // 详情高度
    showSku: false, // 展示sku面板
    sku: {
      tree: [
        {
          k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
          v: []
        }
      ],
      // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
      price: '1.00', // 默认价格（单位元）
      none_sku: true, // 是否无规格商品
      stock_num: 227 // 商品总库存
    },
    goods: {
      // 默认商品 sku 缩略图
      picture: ''
    }
  }),
  mounted() {
    const { iid, id } = this.$route.params
    this.gid = id
    this.queryGoodsDetail(iid)
  },
  watch: {
    loading(newValue) {
      if (newValue) window.addEventListener('scroll', this.scroll)
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.scroll)
  },
  computed: {
    ...mapState({
      uid: (state) => state.userInfo.id
    })
  },
  methods: {
    // 查询商品详情
    async queryGoodsDetail(iid) {
      // 通过iid拿到商品数据
      this.detail = await queryGoodsDetail(iid)
      // 商品的价格
      this.sku.price = this.detail.itemInfo.highNowPrice
      // 商品的图片
      this.goods.picture = this.detail.itemInfo.topImages[0]
      this.loading = true
    },
    scroll() {
      // 页面滚动的高度
      this.scrollTop = document.documentElement.scrollTop
      // 详情部分的高度
      this.goodsDetailTop = this.$refs.goodsDetail.$el.offsetHeight
    },
    handleBuyClicked() {
      console.log('购买')
    },
    // 添加购物车
    async handleAddCartClicked({ goodsId, selectedNum }) {
      const data = await saveCart({
        uid: this.uid,
        num: selectedNum,
        gid: goodsId
      })
      Toast.success(data)
      this.showSku = false
    }
  }
}
</script>

<style lang="less" scoped>
.nav-bar {
  position: fixed;
  .iconfont {
    font-size: 12px;
    color: white;
    padding: 8px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.1);
  }
  .right {
    display: flex;
    justify-content: space-evenly;
  }
}

.scroll-nav-bar {
  background: var(--theme-color);
  .iconfont {
    border-radius: 50%;
    background: rgba(0, 0, 0, 0);
  }

  .center {
    display: flex;
    color: white;
    font-size: 12px;
    text-align: center;
    span {
      flex: 1;
      opacity: 0.5;
    }
    .active {
      opacity: 1;
      .line {
        display: block;
        width: 30%;
        margin: 0 auto;
        border-top: 1px solid white;
      }
    }
  }
}
.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 10px;
  padding: 2px 10px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
  color: white;
  border-radius: 12px;
}
.detail-body {
  padding: 10px 8px;
}
.van-sku-actions {
  .sku-action-btn {
    flex: 1;
    height: 28px;
    font-size: 13px;
  }
}
</style>
